




const vocabularyList = document.getElementById('vocabularyList');
const searchInput = document.getElementById('searchInput');
const addWordBtn = document.getElementById('addWordBtn');
const exportBtn = document.getElementById('exportBtn');
const wordModal = document.getElementById('wordModal');
const modalTitle = document.getElementById('modalTitle');
const wordForm = document.getElementById('wordForm');
const wordIdInput = document.getElementById('wordId');
const frenchInput = document.getElementById('frenchInput');
const chineseInput = document.getElementById('chineseInput');
const categoryInput = document.getElementById('categoryInput');
const cancelBtn = document.getElementById('cancelBtn');
const closeBtn = document.querySelector('.close');


const totalWords = document.getElementById('totalWords');
const todayWords = document.getElementById('todayWords');


let allWords = [];
let searchTimeout = null;


document.addEventListener('DOMContentLoaded', () => {
    console.log('📚 单词本页面加载完成');


    loadVocabulary();
    loadStatistics();


    searchInput.addEventListener('input', handleSearch);
    addWordBtn.addEventListener('click', () => openModal());
    exportBtn.addEventListener('click', handleExport);
    wordForm.addEventListener('submit', handleSubmit);
    cancelBtn.addEventListener('click', closeModal);
    closeBtn.addEventListener('click', closeModal);


    window.addEventListener('click', (e) => {
        if (e.target === wordModal) {
            closeModal();
        }
    });
});




async function loadVocabulary() {
    try {
        const response = await fetch('/api/vocabulary');
        const result = await response.json();

        if (result.success) {
            allWords = result.data;
            displayWords(allWords);
        } else {
            throw new Error(result.error || '加载失败');
        }
    } catch (error) {
        console.error('❌ 加载单词列表失败:', error);
        vocabularyList.innerHTML = `
            <p class="placeholder">加载失败: ${error.message}</p>
        `;
    }
}




async function loadStatistics() {
    try {
        const response = await fetch('/api/stats');
        const result = await response.json();

        if (result.success) {
            totalWords.textContent = result.data.total;
            todayWords.textContent = result.data.today_count;
        }
    } catch (error) {
        console.error('❌ 加载统计失败:', error);
    }
}




function displayWords(words) {
    if (words.length === 0) {
        vocabularyList.innerHTML = `
            <p class="placeholder">暂无单词，开始添加吧！</p>
        `;
        return;
    }

    vocabularyList.innerHTML = words.map(word => `
        <div class="vocab-item" data-id="${word.id}">
            <div class="vocab-content">
                <div class="vocab-french">
                    ${escapeHtml(word.french)}
                    ${word.audio_url ?
                        `<button class="play-audio-btn" onclick="playWordAudio('${word.audio_url}')" style="margin-left: 10px; padding: 4px 10px; background: var(--french-blue); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 12px;">🔊 播放</button>` :
                        `<button class="generate-audio-btn" onclick="generateWordAudio(${word.id})" style="margin-left: 10px; padding: 4px 10px; background: var(--french-red); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 12px;">🎵 生成音频</button>`
                    }
                </div>
                <div class="vocab-chinese">${escapeHtml(word.chinese)}</div>
                <div class="vocab-meta">
                    <span>📁 ${escapeHtml(word.category)}</span>
                    <span>🕐 ${formatDate(word.created_at)}</span>
                </div>
            </div>
            <div class="vocab-actions">
                <button class="edit-btn" onclick="editWord(${word.id})">✏️ 编辑</button>
                <button class="delete-btn" onclick="deleteWord(${word.id})">🗑️ 删除</button>
            </div>
        </div>
    `).join('');
}




function handleSearch(e) {
    const keyword = e.target.value.trim();


    clearTimeout(searchTimeout);

    searchTimeout = setTimeout(async () => {
        if (keyword) {
            try {
                const response = await fetch(`/api/vocabulary/search?q=${encodeURIComponent(keyword)}`);
                const result = await response.json();

                if (result.success) {
                    displayWords(result.data);
                }
            } catch (error) {
                console.error('❌ 搜索失败:', error);
            }
        } else {

            displayWords(allWords);
        }
    }, 300);
}




function openModal(word = null) {
    if (word) {

        modalTitle.textContent = '编辑单词';
        wordIdInput.value = word.id;
        frenchInput.value = word.french;
        chineseInput.value = word.chinese;
        categoryInput.value = word.category;
    } else {

        modalTitle.textContent = '添加单词';
        wordForm.reset();
        wordIdInput.value = '';
    }

    wordModal.classList.add('show');
    frenchInput.focus();
}




function closeModal() {
    wordModal.classList.remove('show');
    wordForm.reset();
}




async function handleSubmit(e) {
    e.preventDefault();

    const wordId = wordIdInput.value;
    const generateAudio = document.getElementById('generateAudioInput').checked;

    const data = {
        french: frenchInput.value.trim(),
        chinese: chineseInput.value.trim(),
        category: categoryInput.value.trim() || '翻译结果',
        generate_audio: generateAudio
    };

    if (!data.french || !data.chinese) {
        alert('请填写法语和中文内容');
        return;
    }


    const submitBtn = e.target.querySelector('button[type="submit"]');
    if (generateAudio) {
        submitBtn.textContent = '保存中（生成音频）...';
        submitBtn.disabled = true;
    }

    try {
        let response;

        if (wordId) {

            response = await fetch(`/api/vocabulary/${wordId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
                credentials: 'include'
            });
        } else {

            response = await fetch('/api/vocabulary', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
                credentials: 'include'
            });
        }

        const result = await response.json();

        if (result.success) {
            const msg = wordId ? '✅ 更新成功！' : '✅ 添加成功！';
            alert(result.audio_url ? msg + '（已生成音频）' : msg);
            closeModal();
            loadVocabulary();
            loadStatistics();
        } else {
            throw new Error(result.error || '操作失败');
        }

    } catch (error) {
        console.error('❌ 操作失败:', error);
        alert('操作失败: ' + error.message);
    } finally {
        submitBtn.textContent = '保存';
        submitBtn.disabled = false;
    }
}




async function editWord(id) {
    const word = allWords.find(w => w.id === id);
    if (word) {
        openModal(word);
    }
}




async function deleteWord(id) {
    if (!confirm('确定要删除这个单词吗？')) {
        return;
    }

    try {
        const response = await fetch(`/api/vocabulary/${id}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ 删除成功！');
            loadVocabulary();
            loadStatistics();
        } else {
            throw new Error(result.error || '删除失败');
        }

    } catch (error) {
        console.error('❌ 删除失败:', error);
        alert('删除失败: ' + error.message);
    }
}




async function handleExport() {
    try {
        window.open('/api/vocabulary/export', '_blank');
    } catch (error) {
        console.error('❌ 导出失败:', error);
        alert('导出失败: ' + error.message);
    }
}




function formatDate(isoString) {
    const date = new Date(isoString);
    const now = new Date();
    const diff = now - date;


    if (diff < 3600000) {
        const minutes = Math.floor(diff / 60000);
        return minutes <= 1 ? '刚刚' : `${minutes}分钟前`;
    }


    if (diff < 86400000) {
        const hours = Math.floor(diff / 3600000);
        return `${hours}小时前`;
    }


    if (date.toDateString() === now.toDateString()) {
        return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }


    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }


    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
}




function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}




async function handleLogout() {
    if (!confirm('确定要登出吗？')) {
        return;
    }

    try {
        const response = await fetch('/api/auth/logout', {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            window.location.href = '/login';
        } else {
            alert('登出失败：' + result.error);
        }
    } catch (error) {
        console.error('登出错误:', error);
        window.location.href = '/login';
    }
}




function playWordAudio(audioUrl) {
    const audio = new Audio(audioUrl);
    audio.play().catch(error => {
        console.error('音频播放失败:', error);
        alert('音频播放失败');
    });
}




async function generateWordAudio(wordId) {
    if (!confirm('确定要为这个单词生成法语发音音频吗？（约消耗10个字符）')) {
        return;
    }

    try {
        const response = await fetch(`/api/vocabulary/${wordId}/generate-audio`, {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ 音频生成成功！');
            loadVocabulary();
        } else {
            throw new Error(result.error || '生成失败');
        }
    } catch (error) {
        console.error('❌ 生成音频失败:', error);
        alert('生成音频失败: ' + error.message);
    }
}


window.editWord = editWord;
window.deleteWord = deleteWord;
window.playWordAudio = playWordAudio;
window.generateWordAudio = generateWordAudio;
window.handleLogout = handleLogout;

